define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
     function debounce(handle, delay) {
          let time = null;
          return function () {
              let self = this,
                  arg = arguments;
              clearTimeout(time);
              time = setTimeout(function () {
                  handle.apply(self, arg);
              }, delay)
          }
      }
    var Controller = {
     index: function () {
                var groupIndex = new Vue({
                    el: "#htmlIndex",
                    data() {
                        return {
                        tableAjax:false,
                        data:[],
                            user:{},
                       screenType: false,
                       orderScreenList: {},
                       orderList: [],
                       currentPage: 1,
                       totalPage: 0,
                       offset: 0,
                       limit: 10,
                       // form搜索
                       searchForm: {
                                                  id:'',
                        name:'',
                        director:'',
                        
manager:'',
                        createtime:[],
                        updatetime:[]
                       },
                       searchFormInit: {
                                                  id:'',
                        name:'',
                        director:'',
                        
manager:'',
                        createtime:[],
                        updatetime:[]
                       },
                       searchOp: {
                                                id:'=',
                        name:'LIKE',
                        director:'=',
                        
manager:'=',
                        createtime:'range',
                        updatetime:'range'
                       },
                      /**时间快捷选取，可删除**/
                       pickerOptions: {
                           shortcuts: [{
                               text: '今天',
                               onClick(picker) {
                                       const start = moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00';
                                       const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                       picker.$emit('pick', [start, end]);
                                   }
                               }, {
                                   text: '昨天',
                                   onClick(picker) {
                                       const start = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                       const end = moment(new Date()).add(-1, 'days').format('YYYY-MM-DD') + ' 23:59:59';
                                       picker.$emit('pick', [start, end]);
                                   }
                               }, {
                                   text: '最近一周',
                                   onClick(picker) {
                                       const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                       const start = moment(new Date()).add(-7, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                       picker.$emit('pick', [start, end]);
                                   }
                               }, {
                                   text: '最近一个月',
                                   onClick(picker) {
                                       const end = moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59';
                                       const start = moment(new Date()).add(-30, 'days').format('YYYY-MM-DD') + ' 00:00:00';
                                       picker.$emit('pick', [start, end]);
                                   }
                               }, {
                                   text: '上月',
                                   onClick(picker) {
                                       const end = moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD') + ' 23:59:59';
                                       const start = moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD') + ' 00:00:00';
                                       picker.$emit('pick', [start, end]);
                                   }
                               }]
                           },
                           

                       }
                    },
                    created() {
                        this.reqOrderList();
                        this.getUser();
                        
                    },
                    methods: {
                        getUser(){
                            let that = this
                            Fast.api.ajax({
                                url: 'users/worktype/getUser',
                                loading: true,
                                type: "POST",
                                data: {

                                }
                            }, function (ret, res) {
                                that.user = res.data
                                console.log(res,'----------')
                                return false;
                            })
                        },
                    //主键及所有数字类型字段排序，你也可以在html中设置其他自定义字段为排序字段
                     sortChange(column) {
                            this.sort = column.prop;
                            this.order = (column.order == 'ascending' ? 'asc' : 'desc');
                            this.reqOrderList();
                        },
                     //重构fastadmin的ajax方法，以便截取接口返回编码
                    ajax(options, success, error) {
                        options = typeof options === 'string' ? {url: options} : options;
                        var index;
                        if (typeof options.loading === 'undefined' || options.loading) {
                            index = Layer.load(options.loading || 0);
                        }
                        options = $.extend({
                            type: "POST",
                            dataType: "json",
                            xhrFields: {
                                withCredentials: true
                            },
                            success: function (ret) {
                                //兼容官方格式数据
                                var resData={};
                                resData.data=ret;
                                success.call(this, resData, resData);
                            }
                        }, options);
                        return $.ajax(options);
                    },
                     /**数据交互非通用代码开始**/
                        
                      /**数据交互非通用代码结束**/

                      //筛选
                        changeSwitch() {
                            this.screenType = !this.screenType;
                        },
                        //清空筛选
                        screenEmpty() {
                            this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit));
                            this.reqOrderList(0,10);
                        },
                        // 搜索条件显隐
                        changeStoreId(val) {
                            if (val) {
                                this.searchForm.base_id = '0';
                            } else {
                                this.searchForm.base_id = '';
                            }
                        },
                        //搜索条件
                       dataFilter(val) {
                            this.searchWhree = val;
                            this.storeDebounceFilter()
                                        },
                          //请求
                        reqOrderList(offset, limit) {
                            var that = this;
                            if (offset == 0 && limit == 10) {
                                that.offset = offset;
                                that.limit = limit;
                            }
                            let filter = {}
                            let op = {}
                            let arratList=[]
                            for (key in that.searchForm) {
                             if(Array.isArray(that.searchForm[key])&&that.searchForm[key]&&arratList.includes(key)){
                                     that.searchForm[key]=that.searchForm[key].join(',');
                               }
                                    if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                               filter[key] = that.searchForm[key];
                                           }
                                           if (that.searchOp[key] == 'range') {
                                               if (that.searchForm[key]&&that.searchForm[key].length > 0) {
                                                   filter[key] = that.searchForm[key].join(' - ');
                                               }
                                           } else if (key == 'status') {
                                               if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                                   filter[key] = that.searchForm[key];
                                               }
                                           }
                            }
                            for (key in filter) {
                                op[key] = that.searchOp[key]
                            }
                            Fast.api.ajax({
                                url: 'users/worktype/index',
                                loading: true,
                                type: 'GET',
                                data: {
                                    filter: JSON.stringify(filter),
                                    op: JSON.stringify(op),
                                    offset: that.offset,
                                    limit: that.limit,
                                    sort:that.sort,
                                    order:that.order
                                }
                            }, function (ret, res) {
                                that.data = res.data.rows;
                                that.totalPage = res.data.total;
                                that.focusi = false;
                                return false;
                            })
                        },
                        //新窗口打开
                        openNewWindow(url) {
                                window.open(Fast.api.cdnurl(url), '_blank');
                            },
                        //操作列，可自定义添加事件
                        baseAction(type, id) {
                            let that = this;
                            switch (type) {
                                case 'create':
                                    Fast.api.open('users/worktype/add', '新建', {
                                        callback() {
                                            that.reqOrderList();
                                        }
                                    })
                                    break;
                                case 'edit':
                                    Fast.api.open('users/worktype/edit?ids=' + id, '编辑', {
                                        callback() {
                                            that.reqOrderList();
                                        }
                                    })
                                    break;
                                case 'del':
                                    that.$confirm('此操作将永久直接删除数据, 是否继续?', '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }).then(() => {
                                        Fast.api.ajax({
                                            url: 'users/worktype/del/ids/' + id,
                                            loading: true,
                                            type: 'POST',
                                        }, function (ret, res) {
                                            that.reqOrderList();

                                        })
                                        return false;
                                    }).catch(() => {
                                        that.$message({
                                            type: 'info',
                                            message: '已取消删除'
                                        });
                                    });
                                    break;
                                     case 'recyclebin':
                                        Fast.api.open('users/worktype/recyclebin?ids=' + id, '回收站', {
                                            callback() {
                                                that.reqOrderList();
                                            }
                                        });
                                        break;
                            }
                        },
                        handleSizeChange(val) {
                            this.offset = 0
                            this.limit = val;
                            this.currentPage = 1;
                            this.reqOrderList()
                        },
                        handleCurrentChange(val) {
                            this.currentPage = val;
                            this.offset = (val - 1) * this.limit;
                            this.reqOrderList()
                        },
                        tableRowClassName({
                            rowIndex
                        }) {
                            if (rowIndex % 2 == 1) {
                                return 'bg-color';
                            }
                            return '';
                        },
                        tableCellClassName({
                            columnIndex
                        }) {
                            if (columnIndex == 1 || columnIndex == 4) {
                                return 'cell-left';
                            }
                            return '';
                        },

                    },

                })
            },
        add: function () {

             Controller.detailInit('add');
        },
        edit: function () {
            Controller.detailInit('edit');
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        detailInit: function (type) {
                    Vue.directive('enterNumber', {
                        inserted: function (el) {
                            let changeValue = (el, type) => {
                                const e = document.createEvent('HTMLEvents')
                                e.initEvent(type, true, true)
                                el.dispatchEvent(e)
                            }
                            el.addEventListener("keyup", function (e) {
                                let input = e.target;
                                let reg = new RegExp('^((?:(?:[1-9]{1}\\d*)|(?:[0]{1}))(?:\\.(?:\\d){0,2})?)(?:\\d*)?$');
                                let matchRes = input.value.match(reg);
                                if (matchRes === null) {
                                    input.value = "";
                                } else {
                                    if (matchRes[1] !== matchRes[0]) {
                                        input.value = matchRes[1];
                                    }
                                }
                                changeValue(input, 'input')
                            });
                        }
                    });
                    function debounce(handle, delay) {
                        let time = null;
                        return function () {
                            let self = this,
                                arg = arguments;
                            clearTimeout(time);
                            time = setTimeout(function () {
                                handle.apply(self, arg);
                            }, delay)
                        }
                    }
                    var baseDetail = new Vue({
                        el: "#formDetail",
                        data() {
                            return {
                                opttype: type,
                                baseFrom: {},
                                director:null,
                                manager:null,
                                user: {},
                                rules: {
                                //默认全部列出，根据业务需求删减即可
                                                           id : [{
                                        required: true,
                                        message: "请设置"+__('Id'),
                                        trigger: "blur"
                                    }],

                        name : [{
                                        required: true,
                                        message: "请设置"+__('Name'),
                                        trigger: "blur"
                                    }],

                        director : [{
                                        required: true,
                                        message: "请设置"+__('Director'),
                                        trigger: "blur"
                                    }],

                        
manager : [{
                                        required: true,
                                        message: "请设置"+__('Manager'),
                                        trigger: "blur"
                                    }],

                        createtime : [{
                                        required: true,
                                        message: "请设置"+__('Createtime'),
                                        trigger: "blur"
                                    }],

                        updatetime : [{
                                        required: true,
                                        message: "请设置"+__('Updatetime'),
                                        trigger: "blur"
                                    }],
                                },
                                baseFromInit: {
                                                                       director:0,

                                    
manager:0,
                                },
                                id: Config.row ? Config.row.id : null,

                                base_address_arr: ['province_name', 'city_name', 'area_name'],
                                base_address_id_arr: ['province_id', 'city_id', 'area_id'],
                                
                            }
                        },
                        mounted() {
                            this.getUser()
                            Controller.api.bindevent();
                            if (this.opttype == 'add') {
                                this.baseFrom = JSON.parse(JSON.stringify(this.baseFromInit));
                                console.log(this.baseFrom)
                            } else {
                                //赋值
                                 this.baseFrom = Config.row;
                                 this.base_id = Config.row.id;
                                  let arratList=[]
                                   arratList.forEach(field => {
                                   if(this.baseFrom[field]){
                                     this.baseFrom[field]=this.baseFrom[field].split(',');
                                    }
                                   })
                                   let jsonList=[]
                                   jsonList.forEach(field => {
                                       this.baseFrom[field] = JSON.parse(this.baseFrom[field] );
                                   })
                                   let dateFormat=[];
                                    dateFormat.forEach(field => {
                                       if(this.baseFrom[field].toString().length>4){
                                           this.baseFrom[field] = moment(this.baseFrom[field]*1000).format('YYYY-MM-DD HH:mm:ss');
                                       }else{
                                           this.baseFrom[field] = moment(this.baseFrom[field]+'').format('YYYY-MM-DD HH:mm:ss');
                                       }
                                   })
                            }
                            
                        },
                        computed: {
                            isAddImage: function () {
                                return this.timeData.images_arr.length;
                            },
                            isAddress: function () {
                                if (this.baseFrom.base_address) {
                                    return this.baseFrom.base_address.length;
                                }
                            },
                        },
                        methods: {
                        getUser(){
                            let that = this
                            Fast.api.ajax({
                                url: 'users/worktype/getUser',
                                loading: true,
                                type: "POST",
                                data: {

                                }
                            }, function (ret, res) {
                                that.user = res.data
                                console.log(res,'----------')
                                return false;
                            })
                        },
                        ajax(options, success, error) {

                            options = typeof options === 'string' ? {url: options} : options;
                            var index;
                            if (typeof options.loading === 'undefined' || options.loading) {
                                index = Layer.load(options.loading || 0);
                            }
                            options = $.extend({
                                type: "POST",
                                dataType: "json",
                                xhrFields: {
                                    withCredentials: true
                                },
                                success: function (ret) {
                                    //兼容官方格式数据
                                    var resData={};
                                    resData.data=ret;
                                    success.call(this, resData, resData);
                                }
                            }, options);
                            return $.ajax(options);
                            },
                            /**数据交互非通用代码开始**/
                            
                            /**数据交互非通用代码结束**/
                            /**通用代码开始，触发函数，不触发则不运行，不占用响应速度，碍事可以删掉**/
                            addImg(type, index, multiple,field,mimetype) {
                              let that = this;
                              parent.Fast.api.open("general/attachment/select?mimetype=" + mimetype+"&multiple="+multiple, "选择图片", {
                                  callback: function (data) {
                                      switch (type) {
                                          case "image":
                                              that.baseFrom[field] = data.url;
                                              break;
                                          case "images":
                                              that.baseFrom[field] = that.baseFrom[field].length>0 ? that.baseFrom[field] + ',' + data.url : data.url;
                                              let arrs = that.baseFrom[field].split(',');
                                              that.baseFrom[field] = arrs;
                                              return;
                                              if (arrs.length > 9) {
                                                  that.baseFrom[field] = arrs.slice(-9)
                                              } else {
                                                  that.baseFrom[field] = arrs
                                              }
                                              break;
                                      }
                                  }
                              });
                              return false;
                          },
                            delImg(type, index,field) {
                               let that = this;
                               switch (type) {
                                   case "image":
                                       that.baseFrom[field] = '';
                                       break;
                                   case "images":
                                       that.baseFrom[field].splice(index, 1);
                                       break;
                               }
                           },
                           /**通用代码结束**/
                            baseSub(type, issub) {
                                let that = this;
                                /**提交前需要格式化的数据集中处理开始**/
                                editorList=[];
                                     editorList.forEach(field => {
                                      that.baseFrom[field] = $("#base-"+field).val();
                                    })
                                yearList=[];
                                    yearList.forEach(field => {
                                      that.baseFrom[field] = moment(this.baseFrom[field]).format('YYYY');
                                   })
                                let subDateFormat=[];
                                   subDateFormat.forEach(field => {
                                      that.baseFrom[field] = moment(this.baseFrom[field]).format('YYYY-MM-DD HH:mm:ss');
                                  })
                                let dateArrFormat=[];
                                     dateArrFormat.forEach(field => {
                                      that.baseFrom[field][0]=moment(that.baseFrom[field][0]).format('YYYY-MM-DD HH:mm:ss');
                                      that.baseFrom[field][1]=moment(that.baseFrom[field][1]).format('YYYY-MM-DD HH:mm:ss');
                                    })
                                  /**提交前需要格式化的数据集中处理结束**/
                                if (type == 'yes') {
                                    this.$refs[issub].validate((valid) => {
                                        if (valid) {
                                            if(that.director!==null){
                                                that.baseFrom.director = that.director
                                            }
                                            if(that.manager!==null){
                                                that.baseFrom.manager = that.manager
                                            }

                                            let subData = JSON.parse(JSON.stringify(that.baseFrom));
                                             //此处可以添加自定义逻辑用以验证提交的数据
                                            if (that.opttype != 'add') {
                                                Fast.api.ajax({
                                                    url: 'users/worktype/edit?ids=' + that.base_id,
                                                    loading: true,
                                                    type: "POST",
                                                    data: {
                                                        data: JSON.stringify(subData)
                                                    }
                                                }, function (ret, res) {
                                                    Fast.api.close({
                                                        data: true
                                                    })
                                                })
                                            } else {
                                                Fast.api.ajax({
                                                    url: 'users/worktype/add',
                                                    loading: true,
                                                    type: "POST",
                                                    data: {
                                                        data: JSON.stringify(subData)
                                                    }
                                                }, function (ret, res) {
                                                    Fast.api.close({
                                                        data: true
                                                    })
                                                })
                                            }
                                        } else {
                                            return false;
                                        }
                                    });
                                } else {
                                    Fast.api.close({ data: false })
                                }
                            },
                        },
                    })
                },
    };
    return Controller;
});
